package com.liu.manag.security;

import com.liu.manag.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.security.Principal;
import java.util.Map;

@Slf4j
public class UserAuthenticationExtractor {
    private static final String USER_EMAIL = "email";
    private static final String ID = "id";
    private static final String NAME = "name";
//    private static final String NAME = "name";

    public static User extract(Principal principal){
        // OAuth2 登录
        if (principal instanceof OAuth2Authentication) {
            return UserAuthenticationExtractor
                    .extract((OAuth2Authentication) principal);
        }

        // 用户名&密码 登录
        if (principal instanceof UsernamePasswordAuthenticationToken) {
            return UserAuthenticationExtractor
                    .extract((UsernamePasswordAuthenticationToken) principal);
        }
        throw new IllegalArgumentException(
                "Principal must either UsernamePasswordAuthenticationToken or OAuth2Authentication");

    }
//    public static User extract(
//            UsernamePasswordAuthenticationToken principal) {
//
//        if (principal.getPrincipal() instanceof UserExt) {
//            UserExt userExt = (UserExt) principal.getPrincipal();
//            return userExt.getPassportUser();
//        }
//
//        throw new IllegalArgumentException(
//
//    }

    public static User extract(OAuth2Authentication authentication) {

        User operator = new User();

        Authentication auth = authentication.getUserAuthentication();
        if (!auth.isAuthenticated()) {
            throw new RuntimeException("Not authenticated");
        }

        if (!(auth instanceof UsernamePasswordAuthenticationToken)) {
            throw new RuntimeException(
                    "Authenticated not extracted by UserInfoTokenServices");
        }

        @SuppressWarnings("unchecked")
        Map<String, String> userInfo = (Map<String, String>) auth.getDetails();
        if (userInfo.containsKey(ID)) {
            operator.setId(Long.valueOf(userInfo.get(ID)));
        }

        if (userInfo.containsKey(NAME)) {
            operator.setUsername(userInfo.get(NAME));
        }

        if (userInfo.containsKey(USER_EMAIL)) {
            operator.setEmail(userInfo.get(USER_EMAIL));
        }

        return operator;
    }

}
